/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jTCaixa.java
 *
 * Created on 24/04/2011, 00:18:22
 */
package forms;

import DAO.DespesasDao;
import Model.Despesas;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author lucas
 */
public class jTCaixa extends javax.swing.JFrame {

    DefaultTableModel tmDespesas = new DefaultTableModel(null, new String []{"Descricao", "Valor"});
    List<Despesas> desp;
    ListSelectionModel lsmDespesas;
    /** Creates new form jTCaixa */
    public jTCaixa() {
        initComponents();
        desabilitaDados();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLDescricao = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTDescricao = new javax.swing.JTextField();
        jTValor = new javax.swing.JTextField();
        jLValor = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jTId = new javax.swing.JTextField();
        jBPesquisar = new javax.swing.JButton();
        jTPesquisar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTTabelaD = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jBNovo = new javax.swing.JButton();
        jBAlterar = new javax.swing.JButton();
        jBExcluir = new javax.swing.JButton();
        jBSalvar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLDescricao.setText("Descrição");

        jLabel3.setText("Despesas");

        jLValor.setText("Valor");

        jLabel1.setText("Id");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLValor)
                        .addGap(52, 52, 52)
                        .addComponent(jTValor, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1)
                            .addComponent(jLDescricao))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTId, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 322, Short.MAX_VALUE))
                            .addComponent(jTDescricao, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLDescricao)
                    .addComponent(jTDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLValor))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        jBPesquisar.setText("Pesquisar");
        jBPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBPesquisarActionPerformed(evt);
            }
        });

        jTTabelaD.setModel(tmDespesas);
        jTTabelaD.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmDespesas = jTTabelaD.getSelectionModel();
        lsmDespesas.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (! e.getValueIsAdjusting()){
                    jTTabelaLinhaSelecionada(jTTabelaD);
                }
            }
        });
        jScrollPane1.setViewportView(jTTabelaD);

        jBNovo.setText("Novo");
        jBNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBNovoActionPerformed(evt);
            }
        });

        jBAlterar.setText("Alterar");
        jBAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAlterarActionPerformed(evt);
            }
        });

        jBExcluir.setText("Excluir");
        jBExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBExcluirActionPerformed(evt);
            }
        });

        jBSalvar.setText("Salvar");
        jBSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSalvarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jBNovo, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jBAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jBExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jBSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBNovo)
                    .addComponent(jBExcluir)
                    .addComponent(jBSalvar)
                    .addComponent(jBAlterar))
                .addContainerGap(32, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addComponent(jTPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jBPesquisar)
                .addGap(24, 24, 24))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jScrollPane1)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(91, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jBPesquisar)
                    .addComponent(jTPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(222, 222, 222))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBNovoActionPerformed
        habilitaDados();
        limpaCampos();
    }//GEN-LAST:event_jBNovoActionPerformed

    public void limpaCampos (){
        jTId.setText("");
        jTDescricao.setText("");
        jTValor.setText("");
    }
    
    private void jBSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSalvarActionPerformed
        if(verificaDados()){
            cadastro();
            JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!");
            desabilitaDados();
            try {
                listarDespesas();
                limpaCampos();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Problemas no botão salvar!");
            }
        }
        
    }//GEN-LAST:event_jBSalvarActionPerformed

    private void jBPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBPesquisarActionPerformed
        
        try {
            listarDespesas();
        } catch (SQLException ex){
            JOptionPane.showMessageDialog(null, "Problemas na Pesquisa: jBPesquisarActionPerformed");
        }
    }//GEN-LAST:event_jBPesquisarActionPerformed

    private void jBExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBExcluirActionPerformed
        try {
            excluirDespesa();
            listarDespesas();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Problemas no botão Excluir");;
        }
    }//GEN-LAST:event_jBExcluirActionPerformed

    private void jBAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAlterarActionPerformed
        try {
            alteraDespesa();
            listarDespesas();
            desabilitaDados();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Problema com o botão alterar!");
        }
    }//GEN-LAST:event_jBAlterarActionPerformed

    public void excluirDespesa() throws SQLException{
        int resp = JOptionPane.showConfirmDialog(this, "Deseja realmente excluir este contato?", "Confirmação", JOptionPane.YES_NO_OPTION);
        if(resp == JOptionPane.YES_OPTION){
            DespesasDao dao = new DespesasDao();
            dao.remove(desp.get(jTTabelaD.getSelectedRow()));
            mostraPesquisa(desp);
            
        }
    }
    
    public void listarDespesas() throws SQLException{
        /*Pega valor digitado no campo pesquisa e faz chamada a mostraPesquisa*/
        DespesasDao dao = new DespesasDao();
        desp = dao.getLista("%" + jTPesquisar.getText() + "%");
        mostraPesquisa(desp);
    }
    
    public void cadastro(){
        /*Cria um novo objeto e atribui valores. Tenta adicionar na tabela.*/
        try {
            Despesas despesas = new Despesas();
            despesas.setDescricao(jTDescricao.getText());
            despesas.setValor(Double.valueOf(jTValor.getText()));

            DespesasDao dao = new DespesasDao();
            dao.adiciona(despesas);
            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Problemas no campo de pesquisa!");
        }
    }
    
    public void desabilitaDados(){
        /*Desabilita campos para edição*/
        jTId.setEditable(false);
        jTDescricao.setEditable(false);
        jTValor.setEditable(false);
    }
    
    public void habilitaDados(){
        /*Habilita campos para edição*/
        jTDescricao.setEditable(true);
        jTValor.setEditable(true);
    }
    
    public boolean verificaDados(){
        /*Verifica se os campos estão em branco*/
        if(!jTDescricao.getText().equals("") && (!jTValor.getText().equals(""))){
            return true;
        }else{
            JOptionPane.showMessageDialog(null, "Campo Descrição ou Valor em branco!");
            return false;
        }
    }
    
    private void jTTabelaLinhaSelecionada (JTable tabela){
        /*Mostra nos campos os valores da linha selecionada*/
        if (tabela.getSelectedRow() != -1) {
            habilitaDados();
            jTId.setText(String.valueOf(desp.get(tabela.getSelectedRow()).getId())); 
            jTDescricao.setText(desp.get(tabela.getSelectedRow()).getDescricao());
            jTValor.setText(String.valueOf(desp.get(tabela.getSelectedRow()).getValor()));    
        }else {
            jTId.setText("");
            jTDescricao.setText("");
            jTValor.setText("");
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new jTCaixa().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBAlterar;
    private javax.swing.JButton jBExcluir;
    private javax.swing.JButton jBNovo;
    private javax.swing.JButton jBPesquisar;
    private javax.swing.JButton jBSalvar;
    private javax.swing.JLabel jLDescricao;
    private javax.swing.JLabel jLValor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTDescricao;
    private javax.swing.JTextField jTId;
    private javax.swing.JTextField jTPesquisar;
    private javax.swing.JTable jTTabelaD;
    private javax.swing.JTextField jTValor;
    // End of variables declaration//GEN-END:variables

    private void mostraPesquisa(List<Despesas> desp) {
        /*Se a tabela for maior que 0, limpa a tabela*/
        while(tmDespesas.getRowCount()>0){
            tmDespesas.removeRow(0);
        }
        /*Se a lista tiver tamanho igual 0, avisa usuário. Se não adiciona lista na tabela.*/
        if(desp.size() == 0){
            JOptionPane.showMessageDialog(null, "Nenhuma despesa cadastrada!");
        }else{
            String[] linha = new String [] {null, null, null};
            for (int i = 0; i < desp.size(); i++) {
                tmDespesas.addRow(linha);
                tmDespesas.setValueAt(desp.get(i).getDescricao(), i, 0);
                tmDespesas.setValueAt(desp.get(i).getValor(), i, 1);
            }
        }
    }
    /* Altera despesa utilizando o valor de Id que está no campo Id do programa*/
    private void alteraDespesa() throws SQLException {
        if(jTTabelaD.getSelectedRow() != -1){
            habilitaDados();
            if(verificaDados()){
                Despesas despesas = new Despesas();
                DespesasDao dao = new DespesasDao();
                despesas.setId(Integer.valueOf(jTId.getText()));
                despesas.setDescricao(jTDescricao.getText());
                despesas.setValor(Double.valueOf(jTValor.getText()));
                dao.altera(despesas);
                JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso");
            }
        }
    }
}
